﻿using System;
using System.Linq;
using Gp.Scripts.Core;
using UnityEngine;

namespace Gp.Scripts.Core {
    public abstract class UnitSubObject : MonoBehaviour {
        public BaseUnit UnitReference { get; private set; }

        public void Init(BaseUnit unitReference) {
            UnitReference = unitReference;
            UnitReference.SubObjectsContainer.Add(this);
            OnInit();
        }

        protected virtual void OnInit() { }


        private void OnDestroy() {
            if (UnitReference) UnitReference.SubObjectsContainer.Remove(this);
        }
    }


    public static class UnitSubObjectExtend {
        public static bool ValidateUnit(this BaseUnit self) {
            return Global.Get<BattleSystem>().IsUnitDestroyed(self);
        }

        public static bool TryGetSubObject<T>(this BaseUnit self, out T res) where T : UnitSubObject {
            res = null;
            if (!self.ValidateUnit()) return false;
            res = GetSubObject<T>(self);
            return res == null;
        }

        public static T GetSubObject<T>(this BaseUnit self) where T : UnitSubObject {
            if (!ValidateUnit(self)) return null;
            return self.SubObjectsContainer.FirstOrDefault(x => x is T) as T;
        }
    }
}